package com.mh.jdbc.util;

import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

import com.alibaba.druid.pool.DruidDataSource;

public class DBUtil {
	//定义数据库连接池
	private static DruidDataSource dataSource;
	static{
		try {
			//实例化数据源
			dataSource = new DruidDataSource();
			Properties pro = new Properties(); 
			//加载配置文件
			pro.load(DBUtil.class.getClassLoader().getResourceAsStream("db.properties"));
			dataSource.setDriverClassName(pro.getProperty("driver"));
			dataSource.setUrl(pro.getProperty("url"));
			dataSource.setUsername(pro.getProperty("username"));
			dataSource.setPassword(pro.getProperty("password"));
			//初始连接数
			dataSource.setInitialSize(1);
			//最小连接数
			dataSource.setMinIdle(1);
			//最大连接数
			dataSource.setMaxActive(30);
			//配置获取连接等待超时的时间
			dataSource.setMaxWait(10000);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	/**
	 * 创建数据库连接
	 * @throws SQLException
	 */
	public static Connection getConnection() throws SQLException{
		return dataSource.getConnection();
	}
	/**
	 * 统一关闭方法
	 * @throws SQLException
	 */
	public static void colse(Object...params){
		for(Object param : params){
			try {
				if(param != null && param instanceof ResultSet){
					ResultSet tmp = (ResultSet) param;
					tmp.close();
				}
				if(param != null && param instanceof Statement){
					Statement tmp = (Statement) param;
					tmp.close();
				}
				if(param != null && param instanceof Connection){
					Connection tmp = (Connection) param;
					tmp.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
	/**
	 * 设置是否自动提交事务
	 * @param conn
	 * @param flag
	 */
	public static void setAutoCommit(Connection conn,boolean flag) {
		try {
			if (conn != null) conn.setAutoCommit(flag);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	/**
	 * 提交
	 * @param conn
	 */
	public static void commit(Connection conn) {
		try {
			if (conn != null) conn.commit();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	/**
	 * 回滚
	 * @param conn
	 */
	public static void rollback(Connection conn) {
		try {
			if (conn != null) conn.rollback();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}
